package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {
    private final static String WX_URL= "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private JwtProperties properties;
    @Resource
    private UserMapper userMapper;
    @Resource
    private  WeChatProperties weChatProperties;
    public UserLoginVO wxLogin(UserLoginDTO dto){
        //调用接口获得用户的openid
        Map<String, String> map = new LinkedHashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(WX_URL, map);
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        if (openid==null||openid==""){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);

        User user = userMapper.selectOne(wrapper);
        //如果是新用户就自动注册
        if (user == null){
            user   = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }


        //为用户生成token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        claims.put("type","user");
        String jwt = JwtUtil.createJWT(properties.getUserSecretKey(), properties.getUserTtl(), claims);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user,userLoginVO);
        userLoginVO.setToken(jwt);
        return userLoginVO;
    }
}
